package com.yuanduan.mplus.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.cj.framework.app.BaseApplication;
import com.cj.framework.util.IOkHttp;
import com.cj.framework.util.Msg;
import com.cj.framework.util.OkHttpImp;
import com.cj.framework.util.RSAUtils;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/9/10.
 */
public class SlideShowView extends FrameLayout implements View.OnClickListener {
    private static final boolean isAutoPlay=true;
    private Context context;
    private ViewPager vp;
    private List<ImageView> imgs;
    private List<View> dots;
    private List<String> urls;
    private int currentItem=0;
    private ScheduledExecutorService slideService;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            vp.setCurrentItem(vp.getCurrentItem()+1);
        }
    };

    private IOkHttp okHttp;
    private com.cj.framework.util.IOkHttp.IHttpCallback callback=new IOkHttp.IHttpCallback() {
        @Override
        public void onResponse(Msg msg, int index) {
            String message=msg.content();
            message= RSAUtils.decryptWithRSA(message);
            dealwithData(message);
//            urls.clear();
//            urls.add("http://www.baidu.com");
//            urls.add("http://www.bing.com");
//            urls.add("http://www.acfun.tv");
//            Glide.with(context)
//                    .load("http://121.42.152.189/apptest/1.png"+"?"+System.currentTimeMillis())
//                    .into(imgs.get(0));
//            Glide.with(context)
//                    .load("http://121.42.152.189/apptest/2.png"+"?"+System.currentTimeMillis())
//                    .into(imgs.get(1));
//            Glide.with(context)
//                    .load("http://121.42.152.189/apptest/3.png"+"?"+System.currentTimeMillis())
//                    .into(imgs.get(2));
        }

        @Override
        public void onError(Exception e) {

        }
    };

    private void dealwithData(String message) {
        urls.clear();
        try {
            JSONArray array=new JSONArray(message);
            urls.add(Config.URL+array.getJSONObject(0).getString("Url"));
            urls.add(Config.URL+array.getJSONObject(1).getString("Url"));
            urls.add(Config.URL+array.getJSONObject(2).getString("Url"));
            for(int i=0;i<3;i++){
                Glide.with(context)
                        .load(Config.URL+array.getJSONObject(i).getString("MainImg"))
                        .asBitmap()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(imgs.get(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public SlideShowView(Context context) {
        this(context,null);
    }

    public SlideShowView(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    public SlideShowView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        init();
        if(isAutoPlay){
            startPlay();
        }
    }

    private void init() {
        LayoutInflater.from(context).inflate(R.layout.viewpager_slide,this,true);
        vp= (ViewPager) findViewById(R.id.vp);
        okHttp=new OkHttpImp();
        //初始化数据
        imgs=new ArrayList<>();
        imgs.add(new ImageView(context));
        imgs.add(new ImageView(context));
        imgs.add(new ImageView(context));
        for(ImageView iv:imgs){
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setOnClickListener(this);
        }
        dots=new ArrayList<>();
        dots.add(findViewById(R.id.dot1));
        dots.add(findViewById(R.id.dot2));
        dots.add(findViewById(R.id.dot3));
        urls=new ArrayList<>();
        urls.add("");urls.add("");urls.add("");

        MyPagerAdapter adapter=new MyPagerAdapter();
        vp.setAdapter(adapter);

        MyPageChangeListener listener=new MyPageChangeListener();
        vp.addOnPageChangeListener(listener);

        HashMap<String,String> hashMap=new HashMap<>();
        okHttp.httpInfoGet(Config.URL+Config.PROMOTION1,callback);
    }

    @Override
    public void onClick(View v) {
        for(int i=0;i<imgs.size();i++){
            if(v==imgs.get(i)){
                Intent intent=new Intent(context,PromotionActivity.class);
                intent.putExtra("url",urls.get(i));
                context.startActivity(intent);
            }
        }
    }

    private void startPlay(){
        slideService= Executors.newSingleThreadScheduledExecutor();
        slideService.scheduleAtFixedRate(new SlideShowTask(),1,8, TimeUnit.SECONDS);
    }

    private void stopPlay(){
        slideService.shutdown();
    }

    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            synchronized (vp){
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    class MyPagerAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.removeView(imgs.get(position%imgs.size()));
            container.addView(imgs.get(position%imgs.size()));
            return imgs.get(position%imgs.size());
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }
    }

    class MyPageChangeListener implements ViewPager.OnPageChangeListener{
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            for(int i=0;i<dots.size();i++){
                if(i==position%imgs.size()){
                    dots.get(i).setBackgroundResource(R.drawable.dot_blue);
                }else{
                    dots.get(i).setBackgroundResource(R.drawable.dot_white);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

}
